package xinya.com.baselibrary.service;

import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.example.yf_a64_api.YF_A64_API_Manager;
import com.github.mjdev.libaums.UsbMassStorageDevice;
import com.github.mjdev.libaums.fs.FileSystem;
import com.github.mjdev.libaums.fs.UsbFile;
import com.github.mjdev.libaums.partition.Partition;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import xinya.com.baselibrary.baseactivity.ToLoginActivity;
import xinya.com.baselibrary.bean.DeviceSetting;
import xinya.com.baselibrary.bean.HeartBean;
import xinya.com.baselibrary.bean.OkObject;
import xinya.com.baselibrary.bean.PushProgramBean;
import xinya.com.baselibrary.bean.program.PositionBean;
import xinya.com.baselibrary.bean.program.Program;
import xinya.com.baselibrary.bean.program.ProgramGetlist;
import xinya.com.baselibrary.bean.program.ResourcesBean;
import xinya.com.baselibrary.bean.program.SceneBean;
import xinya.com.baselibrary.constant.Constant;
import xinya.com.baselibrary.eventbus.EventBusMsg;
import xinya.com.baselibrary.router.RouterUrl;
import xinya.com.baselibrary.router.RouterUtil;
import xinya.com.baselibrary.utils.ACacheX;
import xinya.com.baselibrary.utils.ApiClient;
import xinya.com.baselibrary.utils.FileUtils;
import xinya.com.baselibrary.utils.LogUtil;
import xinya.com.baselibrary.utils.ToastUtils;
import xinya.com.baselibrary.utils.greenDao.MyOpenHelper;
import xinya.com.baselibrary.utils.gson.GenericType;
import xinya.com.baselibrary.utils.gson.GsonUtils;
import xinya.com.baselibrary.utils.gson.HttpResult;
import xinya.com.baselibrary.valueFinal.ProgramCtrType;
import xinya.com.baselibrary.valueFinal.ResourceType;
import xinya.com.db.DaoMaster;
import xinya.com.db.SceneBeanDao;


public class MyService extends Service {
    //自定义U盘读写权限
    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    private UsbMassStorageDevice[] storageDevices;
    private UsbFile cFolder;
    private final static String U_DISK_FILE_NAME = "u_disk.txt";
    private MyOpenHelper devOpenHelper;
    private DaoMaster daoMaster;

    /**
     * Binder实现了IBinder接口
     */
    public class MyBind extends Binder {

        public void getList() {
            MyService.this.getList();
        }

        public void getSetting() {
            MyService.this.getSetting();
        }

        public void startDownLoad(SceneBean sceneBean) {
            MyService.this.startDownLoad(sceneBean);
        }
    }


    @Override
    public IBinder onBind(Intent intent) {
        return new MyBind();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        devOpenHelper = new MyOpenHelper(getApplicationContext(), Constant.DB_NAME, null);
        daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
        registerUDiskReceiver();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        heart();
                        Thread.sleep(30000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        YF_A64_API_Manager yfapi = new YF_A64_API_Manager(this);
        //背光设置
        String blackLight = ACacheX.getAsString(MyService.this, Constant.AcacheKey.setInfo, Constant.AcacheKey.blackLight);
        if (TextUtils.isEmpty(blackLight)){
            yfapi.yfSetLCDOn();
        }else {
            if (Boolean.parseBoolean(blackLight)){
                yfapi.yfSetLCDOn();
            }else {
                yfapi.yfSetLCDOff();
            }
        }
    }

    /**
     * des： 网络请求参数
     * author： ZhangJieBo
     * date： 2017/8/28 0028 上午 9:55
     */
    private OkObject getHeartOkObject() {
        String url = Constant.Url.DEVICE_HEARTBEAT;
        HashMap<String, String> params = new HashMap<>();
        YF_A64_API_Manager yfapi = new YF_A64_API_Manager(this);
        params.put("mac", yfapi.yfgetSerialNumber());
        return new OkObject(params, url);
    }

    /**
     * 心跳
     */
    private void heart() {
        ApiClient.post(MyService.this, getHeartOkObject(), new ApiClient.CallBack() {
            @Override
            public void onSuccess(String s) {
                LogUtil.LogShitou("MyService--onSuccess", "心跳" + s);
                try {
                    HeartBean httpResult = GsonUtils.parseToGenericObject(s, new GenericType<HeartBean>() {
                    });
                    if (httpResult.isStatus()) {
                        String heartLocal = ACacheX.getAsString(MyService.this, Constant.AcacheKey.Heart, Constant.AcacheKey.Heart);
                        String settime = httpResult.getData().getSettime();
                        if (!TextUtils.equals(settime, heartLocal)) {
                            LogUtil.LogShitou("MyService--onSuccess", "心跳服务器端数据有改变");
                            getSetting();
                        }
                        ACacheX.putAsString(MyService.this, Constant.AcacheKey.Heart, Constant.AcacheKey.Heart, settime);
                    } else {
                        LogUtil.LogShitou("MyService--onSuccess心跳", httpResult.getMsg());
                    }
                } catch (Exception e) {
                    LogUtil.LogShitou("MyService--onSuccess", "心跳数据出错");
                }
            }

            @Override
            public void onError() {
                LogUtil.LogShitou("MyService--onError", "心跳失败");
            }
        });
    }

    /**
     * des： 网络请求参数
     * author： ZhangJieBo
     * date： 2017/8/28 0028 上午 9:55
     */
    private OkObject getOkObject() {
        String url = Constant.Url.DEVICE_SETTING;
        HashMap<String, String> params = new HashMap<>();
        YF_A64_API_Manager yfapi = new YF_A64_API_Manager(this);
        params.put("mac", yfapi.yfgetSerialNumber());
        return new OkObject(params, url);
    }

    /**
     * 获取机器设置信息
     */
    private void getSetting() {
        ApiClient.post(MyService.this, getOkObject(), new ApiClient.CallBack() {
            @Override
            public void onSuccess(String s) {
                LogUtil.LogShitou("MyService--onSuccess设置信息", "" + s);
                try {
                    DeviceSetting httpResult = GsonUtils.parseToGenericObject(s, new GenericType<DeviceSetting>() {
                    });
                    if (httpResult.isStatus()) {
                        DeviceSetting.DataBean data = httpResult.getData();
                        if (data!=null){
                            //应用守护
                            int devMacs = data.getDevMacs();
                            ACacheX.putAsString(MyService.this, Constant.AcacheKey.setInfo, Constant.AcacheValue.keepLive, String.valueOf(devMacs == 1));
                            if (devMacs == 1) {
                                Constant.keepLive = true;
                            } else {
                                Constant.keepLive = false;
                            }
                            //开机自启
                            int rootStartSet = data.getRootStartSet();
                            ACacheX.putAsString(MyService.this, Constant.AcacheKey.setInfo, Constant.AcacheValue.openCloseEnable, String.valueOf(rootStartSet == 1));
                            //背光设置
                            int blacklightSet = data.getBlacklightSet();
                            ACacheX.putAsString(MyService.this, Constant.AcacheKey.setInfo, Constant.AcacheKey.blackLight,String.valueOf(blacklightSet==1));
                            YF_A64_API_Manager yfapi = new YF_A64_API_Manager(MyService.this);
                            if (blacklightSet==1){
                                yfapi.yfSetLCDOn();
                            }else {
                                yfapi.yfSetLCDOff();
                            }
                            //亮度
                            int deviceBrightness = data.getDeviceBrightness();

                        }


                    } else {
                    }
                } catch (Exception e) {
                }
            }

            @Override
            public void onError() {
            }
        });
    }

    /**
     * des： 网络请求参数
     * author： ZhangJieBo
     * date： 2017/8/28 0028 上午 9:55
     */
    private OkObject getListOkObject() {
        String url = Constant.Url.PROGRAM_GETLIST;
        HashMap<String, String> params = new HashMap<>();
        YF_A64_API_Manager yfapi = new YF_A64_API_Manager(this);
        params.put("mac", yfapi.yfgetSerialNumber());
//        params.put("mac", "test_xiaozhang");
        return new OkObject(params, url);
    }

    //获取节目列表
    private void getList() {
        ApiClient.post(MyService.this, getListOkObject(), new ApiClient.CallBack() {
            @Override
            public void onSuccess(String s) {
                LogUtil.LogShitou("MyService--onSuccess", "" + s);
                try {
                    HttpResult<ProgramGetlist> httpResult = GsonUtils.parseToGenericObject(s, new GenericType<HttpResult<ProgramGetlist>>() {
                    });
                    if (httpResult.getStatus() == ApiClient.OK) {
                        List<ProgramGetlist.DataBean> list = httpResult.getResult().getData();
                        if (list == null) {
                            list = new ArrayList<>();
                        }
                        if (list.size() == 0) {
                            deleteAll();
                        }
                        for (int i = 0; i < list.size(); i++) {
                            getAdv(list.get(i).getProgram_id(), list.get(i).getScene_type());
                        }
//                        List<SceneBean01> listDb = sceneBeanDao.queryBuilder().list();
//                        for (int i = 0; i < listDb.size(); i++) {
//
//                        }
                    } else if (httpResult.getStatus() == ApiClient.OUT) {
                        ToLoginActivity.toLoginActivity(MyService.this);
                    } else {
                        Toast.makeText(MyService.this, httpResult.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(MyService.this, "数据出错", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError() {
                Toast.makeText(MyService.this, "请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * des： 网络请求参数
     * author： ZhangJieBo
     * date： 2017/8/28 0028 上午 9:55
     */
    private OkObject getOkObject(long id) {
        String url = Constant.Url.PROGRAM_GET;
        HashMap<String, String> params = new HashMap<>();
        params.put("id", String.valueOf(id));
        YF_A64_API_Manager yfapi = new YF_A64_API_Manager(this);
        params.put("mac", yfapi.yfgetSerialNumber());
        return new OkObject(params, url);
    }

    /**
     * 获取广告信息
     */
    private void getAdv(long id, int sceneType) {
        SceneBeanDao sceneBeanDao = daoMaster.newSession().getSceneBeanDao();
        List<SceneBean> sceneBean01List = sceneBeanDao.queryBuilder().where(SceneBeanDao.Properties.Id.eq(id)).list();
        if (sceneBean01List != null && sceneBean01List.size() > 0) {
            SceneBean sceneBean = sceneBean01List.get(0);
            if (sceneBean.getDownloadComplete()) {
                LogUtil.LogShitou("MyService--getAdv", "该节目已下载");
                if (sceneType == 1 && sceneBean.getScreen01() != 1) {
                    sceneBean.setScreen01(1);
                    sceneBeanDao.update(sceneBean);
                } else if (sceneType == 2 && sceneBean.getScreen02() != 1) {
                    sceneBean.setScreen02(1);
                    sceneBeanDao.update(sceneBean);
                }
                EventBus.getDefault().post(new EventBusMsg(Constant.EventKey.NEW_ADV, sceneBean));
                return;
            } else {
                LogUtil.LogShitou("MyService--getAdv", "该节目已存在");
                if (sceneType == 1 && sceneBean.getScreen01() != 1) {
                    sceneBean.setScreen01(1);
                    sceneBeanDao.update(sceneBean);
                } else if (sceneType == 2 && sceneBean.getScreen02() != 1) {
                    sceneBean.setScreen02(1);
                    sceneBeanDao.update(sceneBean);
                }
                return;
            }
        }
        ApiClient.get(this, getOkObject(id), new ApiClient.CallBack() {
            @Override
            public void onSuccess(String s) {
//                LogUtil.LogShitou("MyService--onSuccess", "" + s);
                try {
                    HttpResult<Program> httpResult = GsonUtils.parseToGenericObject(s, new GenericType<HttpResult<Program>>() {
                    });
                    if (httpResult.getStatus() == ApiClient.OK) {
                        Program program = httpResult.getResult();
                        if (program != null) {
                            SceneBean scene = program.getScene();
                            String size = program.getProgram().getPower();
                            scene.setWidth(Float.parseFloat(size.split("X")[0]));
                            scene.setHeight(Float.parseFloat(size.split("X")[1]));
                            List<PositionBean> programPosition = program.getPosition();
                            List<List<ResourcesBean>> programResources = program.getResources();
                            for (int i = 0; i < programPosition.size(); i++) {
                                List<ResourcesBean> resourcesBeanListNew = new ArrayList<>();
                                for (int j = 0; j < programResources.size(); j++) {
                                    List<ResourcesBean> resourcesBeanList = programResources.get(j);
                                    for (int k = 0; k < resourcesBeanList.size(); k++) {
                                        if (TextUtils.equals(resourcesBeanList.get(k).getDataId(), programPosition.get(i).getDataId())) {
                                            resourcesBeanListNew.add(resourcesBeanList.get(k));
                                        }
                                    }
                                }
                                programPosition.get(i).setResourcesBeans(resourcesBeanListNew);
                            }
                            scene.setPositionBeans(programPosition);
                            SceneBeanDao sceneBean01Dao = daoMaster.newSession().getSceneBeanDao();
                            List<SceneBean> sceneBean01List = sceneBeanDao.queryBuilder().where(SceneBeanDao.Properties.Id.eq(scene.getId())).list();
                            if (sceneBean01List != null && sceneBean01List.size() > 0) {
                                return;
                            }
                            if (sceneType == 1 && scene.getScreen01() != 1) {
                                scene.setScreen01(1);
                            } else if (sceneType == 2 && scene.getScreen02() != 1) {
                                scene.setScreen02(1);
                            }
                            sceneBean01Dao.insertOrReplace(scene);
                            startDownLoad(scene);
                        }
                    } else if (httpResult.getStatus() == ApiClient.OUT) {
                        ToLoginActivity.toLoginActivity(MyService.this);
                    } else {
                        Toast.makeText(MyService.this, httpResult.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(MyService.this, "数据出错", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError() {
                Toast.makeText(MyService.this, "请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 开启下载
     */
    private void startDownLoad(SceneBean scene) {
        try {
            SceneBeanDao sceneBeanDao = daoMaster.newSession().getSceneBeanDao();
            List<SceneBean> sceneBean01List = sceneBeanDao.queryBuilder().where(SceneBeanDao.Properties.Id.eq(scene.getId())).list();
            if (sceneBean01List != null && sceneBean01List.size() > 0) {
                if (sceneBean01List.get(0).getDownloadComplete()) {
                    LogUtil.LogShitou("MyService--startDownLoad", "改节目已下载");
                    return;
                }
            }
            LogUtil.LogShitou("MyService--startDownLoad", "节目开始下载" + scene.getId());
//        ResourcesBeanDao resourcesBeanDao = daoMaster.newSession().getResourcesBeanDao();
//        List<ResourcesBean> resourcesBeanList = resourcesBeanDao.queryBuilder().where(ResourcesBeanDao.Properties.Keyid.eq(scene.getId())).list();
//        LogUtil.LogShitou("MyService--startDownLoad", "" + GsonUtils.parseObject(resourcesBeanList));
            String systemFilePathExcel = FileUtils.getSystemFilePath(MyService.this) + "/adv";
            OkDownload.getInstance().setFolder(systemFilePathExcel);
            final int[] sum = {0};
            final int[] sumDownLoad = {0};
            for (int i = 0; i < scene.getPositionBeans().size(); i++) {
                List<PositionBean> positionBeans = scene.getPositionBeans();
                List<ResourcesBean> resourcesBeanList = positionBeans.get(i).getResourcesBeans();
                for (int k = 0; k < resourcesBeanList.size(); k++) {
                    LogUtil.LogShitou("MyService--startDownLoad", "num+++++++");
                    sum[0]++;
                    ResourcesBean resourcesBean = resourcesBeanList.get(k);
                    if (
                            (resourcesBean.getType() == ResourceType.img ||
                                    resourcesBean.getType() == ResourceType.video) &&
                                    TextUtils.isEmpty(resourcesBean.getFilePath()
                                    )
                    ) {
                        String downloadurl = resourcesBean.getDownloadurl();
//                LogUtil.LogShitou("MyService--startDownLoad", "下载" + downloadurl);
                        GetRequest request = OkGo.get(downloadurl);
                        String tag = resourcesBean.getId() + "@@@" + positionBeans.get(i).getId() + "@@@" + scene.getId();
                        String[] splitDown = downloadurl.split("/");
                        File file = new File(systemFilePathExcel, splitDown[splitDown.length - 1]);
                        if (file.exists()) {
                            resourcesBean.setFilePath(file.getPath());
                            sumDownLoad[0]++;
                            if (sum[0] == sumDownLoad[0]) {
                                scene.setDownloadComplete(true);
                                sceneBeanDao.insertOrReplace(scene);
                                LogUtil.LogShitou("MyService--onFinish", "节目全部下载" + scene.getId());
                                EventBus.getDefault().post(new EventBusMsg(Constant.EventKey.NEW_ADV, scene));
                            }
                            return;
                        }
                        DownloadTask downloadTask = OkDownload.request(tag, request)
                                .save()
                                .fileName(splitDown[splitDown.length - 1])
                                .register(new DownloadListener(tag) {
                                    @Override
                                    public void onStart(Progress progress) {
                                        LogUtil.LogShitou("MyService--onStart", "开始");
                                    }

                                    @Override
                                    public void onProgress(Progress progress) {
                                        LogUtil.LogShitou("MyService--onProgress", "" + progress.fraction);
                                    }

                                    @Override
                                    public void onError(Progress progress) {
                                        LogUtil.LogShitou("MyService--onError", "出错");
                                    }

                                    @Override
                                    public void onFinish(File file, Progress progress) {
                                        LogUtil.LogShitou("MyService--onFinish", "单个资源下载完成" + file.getPath() + " tag " + tag + " scene " + scene.getId());
                                        String rescourceID = tag.toString().split("@@@")[0];
                                        String positionID = tag.toString().split("@@@")[1];
                                        for (int i = 0; i < resourcesBeanList.size(); i++) {
                                            if (TextUtils.equals(rescourceID, String.valueOf(resourcesBeanList.get(i).getId()))) {
                                                resourcesBeanList.get(i).setFilePath(file.getPath());
                                                break;
                                            }
                                        }
                                        LogUtil.LogShitou("MyService--onFinish", "" + GsonUtils.parseObject(resourcesBeanList));
                                        sumDownLoad[0]++;
                                        LogUtil.LogShitou("MyService--onFinish", "sumDownLoad" + sumDownLoad[0]);
                                        LogUtil.LogShitou("MyService--onFinish", "sum" + sum[0]);
                                        if (sum[0] == sumDownLoad[0]) {
                                            scene.setDownloadComplete(true);
                                            SceneBeanDao sceneBeanDao = daoMaster.newSession().getSceneBeanDao();
                                            sceneBeanDao.insertOrReplace(scene);
                                            LogUtil.LogShitou("MyService--onFinish", "节目全部下载" + scene.getId());
                                            EventBus.getDefault().post(new EventBusMsg(Constant.EventKey.NEW_ADV, scene));
                                        }
                                    }

                                    @Override
                                    public void onRemove(Progress progress) {
//                                LogUtil.LogShitou("MyService--onRemove", "移除");
                                    }
                                });
                        downloadTask.start();
                    } else {
                        sumDownLoad[0]++;
                    }
                }
            }
            if (sum[0] == sumDownLoad[0]) {
                scene.setDownloadComplete(true);
                sceneBeanDao.insertOrReplace(scene);
                LogUtil.LogShitou("MyService--onFinish", "节目全部下载" + scene.getId());
                EventBus.getDefault().post(new EventBusMsg(Constant.EventKey.NEW_ADV, scene));
            }
        } catch (Exception e) {
            LogUtil.LogShitou("MyService--startDownLoad", "下载节目出错");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        Intent intent = new Intent();
        intent.setClass(this, MyServiceX.class);
        startService(intent);
        if (mOtgReceiver != null) {
            unregisterReceiver(mOtgReceiver);
        }
    }

    /**
     * @description OTG广播注册
     * @author ldm
     * @time 2017/9/1 17:19
     */
    private void registerUDiskReceiver() {
        //监听otg插入 拔出
        IntentFilter usbDeviceStateFilter = new IntentFilter();
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(mOtgReceiver, usbDeviceStateFilter);
        //注册监听自定义广播
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        registerReceiver(mOtgReceiver, filter);
    }

    /**
     * @description OTG广播，监听U盘的插入及拔出
     * @author ldm
     * @time 2017/9/1 17:20
     * @param
     */
    private BroadcastReceiver mOtgReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTION_USB_PERMISSION://接受到自定义广播
                    UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    //允许权限申请
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (usbDevice != null) {
                            //用户已授权，可以进行读取操作
//                            readDevice(getUsbMass(usbDevice));
                            LogUtil.LogShitou("MyService--onReceive", "用户已授权，可以进行读取操作");
                        } else {
//                            showToastMsg("没有插入U盘");
                            LogUtil.LogShitou("MyService--onReceive", "没有插入U盘");
                        }
                    } else {
//                        showToastMsg("未获取到U盘权限");
                        LogUtil.LogShitou("MyService--onReceive", "未获取到U盘权限");
                    }
                    break;
                case UsbManager.ACTION_USB_DEVICE_ATTACHED://接收到U盘设备插入广播
                    UsbDevice device_add = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (device_add != null) {
                        //接收到U盘插入广播，尝试读取U盘设备数据
                        LogUtil.LogShitou("MyService--onReceive", "接收到U盘插入广播，尝试读取U盘设备数据");
                        redUDiskDevsList(context);
                        ToastUtils.showToast(context, "检查到U盘插入");
                        RouterUtil.getPostcardWithTransition(context, RouterUrl.Main.main_home)
                                .withBoolean(Constant.IntentKey.USB_FROM, true)
                                .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                                .navigation();
                    }
                    break;
                case UsbManager.ACTION_USB_DEVICE_DETACHED://接收到U盘设设备拔出广播
//                    showToastMsg("U盘已拔出");
                    LogUtil.LogShitou("MyService--onReceive", "U盘已拔出");
                    ToastUtils.showToast(context, "U盘已拔出");
                    EventBus.getDefault().post(new EventBusMsg(Constant.EventKey.closeUsb));
                    break;
            }
        }
    };

    /**
     * @param context
     * @description U盘设备读取
     * @author ldm
     * @time 2017/9/1 17:20
     */
    private void redUDiskDevsList(Context context) {
        //设备管理器
        UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        //获取U盘存储设备
        storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);

        LogUtil.LogShitou("MyService--redUDiskDevsList", "storageDevices.length " + storageDevices.length);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        //一般手机只有1个OTG插口
        for (UsbMassStorageDevice device : storageDevices) {
            //读取设备是否有权限
            if (usbManager.hasPermission(device.getUsbDevice())) {
                LogUtil.LogShitou("MyService--redUDiskDevsList", "111111111");
                readDevice(device);
            } else {
                //没有权限，进行申请
                LogUtil.LogShitou("MyService--redUDiskDevsList", "222222222");
                usbManager.requestPermission(device.getUsbDevice(), pendingIntent);
            }
        }
        if (storageDevices.length == 0) {
            LogUtil.LogShitou("MyService--redUDiskDevsList", "333333333");
            ToastUtils.showToast(context, "请插入可用的U盘");
        }
    }

    private void readDevice(UsbMassStorageDevice device) {
        try {
            device.init();//初始化
            //设备分区
            Partition partition = device.getPartitions().get(0);
            //文件系统
            FileSystem currentFs = partition.getFileSystem();
            currentFs.getVolumeLabel();//可以获取到设备的标识
            //通过FileSystem可以获取当前U盘的一些存储信息，包括剩余空间大小，容量等等
            Log.e("Capacity: ", currentFs.getCapacity() + "");
            Log.e("Occupied Space: ", currentFs.getOccupiedSpace() + "");
            Log.e("Free Space: ", currentFs.getFreeSpace() + "");
            Log.e("Chunk size: ", currentFs.getChunkSize() + "");
            cFolder = currentFs.getRootDirectory();//设置当前文件对象为根目录
            readFromUDisk();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void readFromUDisk() {
        UsbFile[] usbFiles = new UsbFile[0];
        try {
            usbFiles = cFolder.listFiles();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (null != usbFiles && usbFiles.length > 0) {
            for (UsbFile usbFile : usbFiles) {
                LogUtil.LogShitou("MyService--readFromUDisk", "" + usbFile.getName());
                if (usbFile.getName().equals(U_DISK_FILE_NAME)) {
                }
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventReceiver(EventBusMsg eventBusMsg) {
        switch (eventBusMsg.key) {
            case Constant.EventKey.keepLive:
                new Handler().postDelayed(() -> {
                    if (Constant.keepLive) {
                        RouterUtil.getPostcardWithTransition(MyService.this, RouterUrl.Main.main_home)
                                .navigation();
                    }
                }, 30000);
                break;
            case Constant.EventKey.pushProgram:
                PushProgramBean pushProgramBean = (PushProgramBean) eventBusMsg.value;
                LogUtil.LogShitou("MyService--onEventReceiver", GsonUtils.parseObject(pushProgramBean));
                PushProgramBean.ProgramstrBean programstr = pushProgramBean.getProgramstr();
                if (ProgramCtrType.add == pushProgramBean.getType()) {
                    for (int i = 0; i < programstr.getList1().size(); i++) {
                        getAdv(programstr.getList1().get(i), 1);
                    }
                    for (int i = 0; i < programstr.getList2().size(); i++) {
                        getAdv(programstr.getList2().get(i), 2);
                    }
                } else if (ProgramCtrType.addX == pushProgramBean.getType()) {

                } else if (ProgramCtrType.del == pushProgramBean.getType()) {

                } else if (ProgramCtrType.clear == pushProgramBean.getType()) {
                    deleteAll();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 删除所有本地节目
     */
    private void deleteAll() {
        EventBus.getDefault().post(new EventBusMsg(Constant.EventKey.clearAll));
        SceneBeanDao sceneBeanDao = daoMaster.newSession().getSceneBeanDao();
        sceneBeanDao.deleteAll();
        OkDownload.getInstance().removeAll(true);
        String path = FileUtils.getSystemFilePath(MyService.this) + "/adv";
        FileUtils.deleteFile(new File(path));
    }
}